package com.dongdongshop.index;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdong.pojo.TbSeller;
import com.dongdong.service.LoginService;
import com.dongdongshop.configresult.Result;
import com.dongdongshop.em.ResultEnum;
import com.dongdongshop.exception.LonginException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller
@RequestMapping("login")
public class LoginController {


    @Reference
    private LoginService loginService;


    //  注册
    @RequestMapping("denglu")
    @ResponseBody
    public Result denglu(TbSeller tbSeller){
        System.out.println(tbSeller);
        String lname = tbSeller.getLname();
        tbSeller.setSellerId(lname);
        tbSeller.setStatus("0");
        tbSeller.setAddress(1L);
        tbSeller.setCreateTime(new Date());
        tbSeller.setSalt("bb044d");
        tbSeller.setPassword("fd49f91a8bb23a9031bcfbc8ba3b0d9a");
        boolean b = loginService.insert(tbSeller);
        if(b){
            return Result.builResult(ResultEnum.SUCCESS);
        }
        return Result.builResult(ResultEnum.ERROR);
    }

    //    校验用户名是否存在
    @RequestMapping("verify")
    @ResponseBody
    public Result verify(String lname){
        boolean b = loginService.selectName(lname);
        if (b){
            return Result.builResult(ResultEnum.SUCCESS);
        }
        return Result.builResult(ResultEnum.ERROR);
    }

    //    登录
    @RequestMapping("entry")
    public String entry(String lname,String password,Model m){
//      借助shiro登录
//         创建subject
        Subject subject = SecurityUtils.getSubject();
//        封装token
        UsernamePasswordToken token = new UsernamePasswordToken(lname,password);
        try {
            subject.login(token);
        }catch (UnknownAccountException a){
            m.addAttribute("msg","账号错误");
            return "/shoplogin";
        }catch (IncorrectCredentialsException b){
            m.addAttribute("msg","密码错误");
            return "/shoplogin";
        }catch (LonginException e){
            m.addAttribute("msg",e.getMessage());
            return "/shoplogin";
        }
        return "/admin/index";
    }
}
